package com.hhit.zhgd.utils

import jakarta.servlet.http.HttpServletRequest
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Random
import kotlin.reflect.KVisibility
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible

fun String.strToIntArr(regex:String):IntArray {
    val strArr = this.split(regex)
    val intArr = IntArray(strArr.size)
    for (i in strArr.indices) {
        intArr[i] = strArr[i].toInt()
    }
    return intArr
}

/**
 * 字符串转数组
 * "[1,2,3]" => arraylist(1,2,3)
 */
fun String.toIntArr():List<Int> {
    return if (this.startsWith("[") && this.endsWith("]")) {
        val arrStr = this.substring(1, this.length - 1)
        val result = ArrayList<Int>()
        arrStr.split(",").forEach {
            result.add(it.trim().toInt())
        }
        result
    } else {
        arrayListOf()
    }
}

fun getRandomString(length:Int):String{
    val string = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    val random = Random()
    val sb = StringBuffer()
    for (i in 0 until length) {
        val index = random.nextInt(string.length)
        sb.append(string[index])
    }
    return sb.toString()
}


fun HttpServletRequest.getClientIp(): String {
    var ip: String? = this.getHeader("X-Forwarded-For")
    ip = ip ?: this.getHeader("Proxy-Client-IP")
    ip = ip ?: this.getHeader("WL-Proxy-Client-IP")
    ip = ip ?: this.getHeader("HTTP_CLIENT_IP")
    ip = ip ?: this.getHeader("HTTP_X_FORWARDED_FOR")
    ip = ip ?: this.remoteAddr

    // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按','分割
    ip = ip?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()?.get(0)
        ?: ""

    // 如果ip还是"unknown"，则返回空字符串
    return if (ip != "unknown") ip else ""
}


/**
 * 将菜单转成树形结构
 */
fun menuToTree(menus: List<HashMap<String, Any?>>, rootId:Int): List<HashMap<String, Any?>> {
    val list = ArrayList<HashMap<String, Any?>>()
    menus.forEach { menu ->
        if (menu["parent_id"].toString().toInt() == rootId) {
            val subList = menuToTree(menus, menu["id"].toString().toInt())
            menu["children"] = subList
            list.add(menu)
        }
    }
    return list
}


fun <T:Any> T.toMap():HashMap<String,Any?> {
    val result = HashMap<String,Any?>()

    for (property in this::class.memberProperties) {
        if (property.visibility == KVisibility.PRIVATE) {
            property.isAccessible = true
        }

        result[property.name] = property.getter.call(this)
    }

    return result
}


fun Date.formatString(format:String):String {
    val simpleDateFormat = SimpleDateFormat(format)
    return simpleDateFormat.format(this)
}

fun String.formatDate(format:String):Date {
    val simpleDateFormat = SimpleDateFormat(format)
    return simpleDateFormat.parse(this)
}

fun Date.compare(date:Date):Int {
    if (this.time<date.time) {
        return -1
    } else if (this.time > date.time) {
        return 1
    }
    return 0
}

















